package com.stu.day18;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

/**
 * @author zy
 * @date 2025/2/20 14:38
 */
public class ConstructorDemo {
    public static void main(String[] args) {
        Class<?> c;
        try {
            c = Class.forName("com.stu.day18.User");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        Constructor<?>[] constructor = c.getConstructors();
        for (Constructor<?> c1 : constructor) {
            System.out.print(Modifier.toString(c1.getModifiers())+" ");  // 修饰符
            System.out.print(c1.getName()+" ");  // 构造方法权限命名
//            System.out.print(c1);  // 构造方法及其参数

            Class<?>[] parameterTypes = c1.getParameterTypes();  // 构造方法参数列表
            for (Class<?> parameterType : parameterTypes) {
                System.out.print(parameterType.getSimpleName() + " ");
            }
            System.out.println();
        }

        try {
            Constructor c2 = c.getConstructor();  // 空参构造
            User user1 = (User) c2.newInstance();
            System.out.println(user1);

            Constructor c3 = c.getConstructor(Integer.class);  // 指定参数构造
            User user2 = (User) c3.newInstance(1);
            System.out.println(user2);

        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
}
